import React, {Component} from 'react';
import {connect} from "react-redux";
import {
	decrement, increment, incrementAsync
} from '../../redux/actions/count';

import './index.css';

class Count extends Component {

	add = () => {
		const {value} = this.selectValue;
		this.props.increment(value * 1);
	}

	minus = () => {
		const {value} = this.selectValue;
		this.props.decrement(value * 1);
	}

	addIfOdd = () => {
		const {value} = this.selectValue;
		if (this.props.sum % 2 !== 0) {
			this.props.increment(value * 1);
		}
	}

	addAsync = () => {
		const {value} = this.selectValue;
		this.props.incrementAsync(value * 1, 1000)
	}

	render() {


		return (
			<div>
				<h2>我是Count组件</h2>
				<h4>当前求和为: {this.props.sum}</h4>
				<h4>当前人数为: {this.props.personNums}</h4>
				<select className="sel" ref={c => this.selectValue = c}>
					<option value="1">1</option>
					<option value="2">2</option>
					<option value="3">3</option>
					<option value="4">4</option>
				</select>
				<button onClick={this.add}>点我＋</button>
				<button onClick={this.minus}>点我-</button>
				<button onClick={this.addIfOdd}>当前求和为奇数时＋</button>
				<button onClick={this.addAsync}>异步＋</button>
			</div>
		);
	}
}

const mapStateToProps = state => ({
	sum: state.count,
	personNums: state.persons.length
})

const mapDispatchToProps = {
	increment,
	decrement,
	incrementAsync,
}

// 如果当前组件需要跟 reducx交互, 就借助 react-redux提供的connect方法处理!
export default connect(
	mapStateToProps,
	mapDispatchToProps
)(Count);

